<?php
namespace app\substation\controller;
use app\substation\controller\Base;
use think\Session;
use think\Request;
class Freight extends Base{
	
	public function index()
	{
		$freight = Db("freight")
			->alias("f")
			->join("__USER_GROUP__ ug","ug.ug_id = f.ug_id","left")
			->join("__WAREHOUSE__ w","w.w_id = f.w_id","left")
			->where($this->__SUBID_WHERE__)->order("f_id desc")->select();
		$this->assign("freight",$freight);
		return view();
	}

	public function del()
	{
		if(Request::instance()->isAjax()){
			$id = safe_string(trim(input('id')));
			if(empty($id)){
				eyJson($this->__LANGCONFIG__['common_error_id']);
			}

			$res = Db("freight")->where($this->__SUBID_WHERE__." and f_id = {$id}")->delete();
			if($res){
				eyJson("删除运费模板成功！","success");
			}else{
				eyJson("ERROR：删除运费模板失败！");
			}
			
		}
	}
	
	public function add()
	{
		
		if(Request::instance()->isAjax()){
			$f_id      = safe_string(trim(input('f_id')));
			$money      = safe_string(trim(input('money')));
			$status     = safe_string(trim(input('status')));
			$content     = safe_string(trim(input('content')));
			
			$freight = Db("freight")->where("f_id = {$f_id}")->find();
			
			$freight_ = Db("freight")->where($this->__SUBID_WHERE__." and ug_id = {$freight['ug_id']} and w_id = {$freight['w_id']}")->find();
			
			if(!empty($freight_)){
				eyJson("ERROR:此群组已添加了此仓库的运费模板，不能重复添加！");
			}
			
			$money = $money + $freight['f_money'];
			
			$MODEL_DATA = array(
				'sub_id' => $this->__SUBID__,
				'ug_id'   => $freight['ug_id'],
				'w_id' => $freight['w_id'],
				'f_addtime' => date("Y-m-d H:i:s"),
				'f_money'  => $money,
				'f_status' => 1,
				'f_content' =>$content,
			);
		
			$res = Db("freight")->insert($MODEL_DATA);
			if($res){
				eyJson("添加运费模板成功！","success");
			}else{
				eyJson("ERROR:添加运费模板失败！");
			}
		}
		
		$freight = Db("freight")
					->alias("f")
					->join("__USER_GROUP__ ug","f.ug_id = ug.ug_id","left")
					->join("__WAREHOUSE__ w","f.w_id = w.w_id","left")
					->where("f.f_status = 1 and f.sub_id = 0")
					->order("w.w_sort asc,f.f_id asc")
					->select();
		$this->assign("freight",$freight);
		return view();
	}

}